package com.southwind.springboottest.study.Java中通讯.udp协议;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpClientExample {

    public static void main(String[] args) throws Exception {
        // 创建一个 UDP 套接字
        DatagramSocket socket = new DatagramSocket();

        // 要发送的消息
        String message = "Hello, UDP!";
        InetAddress serverAddress = InetAddress.getByName("localhost");

        // 创建数据包，包含消息内容，目标服务器地址和端口
        DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, serverAddress, 9876);

        // 发送数据包
        socket.send(sendPacket);

        byte[] receiveData = new byte[1024]; // 缓冲区，用于接收数据

        // 创建数据包，用于接收响应
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

        // 接收响应数据包
        socket.receive(receivePacket);

        // 解析响应内容
        String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
        System.out.println("UDP Response: " + response);

        // 关闭套接字
        socket.close();
    }
}

